<template>
    <div class="w-full h-full">
        <div id="map" style="width: 100%; height: 100%" @touchstart="dragMapStart" @touchend="dragMapEnd"></div>
        <div class="w-40.6rem search absolute top-5.5rem left-5.5rem z-10000">
            <div class="flex items-center px-3.5rem py-2.2rem">
                <SvgIcon class="w-2.6rem h-3rem" local-icon="search" />
                <input type="text"
                    class="ml-1.6rem bg-transparent text-2.2rem text-white border-none focus:border-none focus:outline-none"
                    placeholder="搜索目的地" @input="getSuggestions" @focus="focusInput" v-model="searchKeyword" />
            </div>
            <div class="w-full h-0.2rem bg-op2"></div>
            <div class="px-3.5rem" v-if="suggestionRoutes.length === 0 && recommondRoutes.length === 0">
                <div class="flex items-center text-white py-2rem cursor-pointer" @click="goHome(true)">
                    <SvgIcon class="w-2.3rem h-2.5rem" local-icon="home" />
                    <span class="text-2.2rem ml-1.6rem">回家</span>
                </div>
                <div class="w-full h-0.1rem bg-op2"></div>
                <div class="flex items-center text-white py-2rem cursor-pointer" @click="goCompany(true)">
                    <SvgIcon class="w-2.1rem h-2.4rem" local-icon="company" />
                    <span class="text-2.2rem ml-1.6rem">去公司</span>
                </div>
            </div>
            <div class="px-3.5rem ">

                <template v-for="(item, index) in suggestionRoutes" v-if="recommondRoutes.length == 0">
                    <div class="flex  flex-col justify-between ml-1rem text-white py-0.5rem cursor-pointer"
                        @click="searchDrivingRoute(item.location, index, item.address)">
                        <div class="text-2.2rem text-white ">{{ item.address }}</div>
                        <div class="text-1.8rem text-#FFFFFF99 ">{{ item.title }}</div>
                    </div>
                    <div class="w-full h-0.1rem bg-op2 " v-if="index !== suggestionRoutes.length - 1"></div>
                </template>
                <template v-for="(item, index) in recommondRoutes">
                    <div class="flex  flex-col justify-between ml-1rem text-white py-0.5rem cursor-pointer"
                        @click="setActivateRecommondRoute(index)">
                        <div class="flex items-center justify-between text-red">
                            <div class="text-2.2rem  "
                                :class="index == activateRecommondRoute ? 'text-#107CFB' : 'text-white'">路线{{ index + 1
                                }}：{{
                                    item.duration }}分钟</div>
                            <div class="text-1.8rem  flex items-center"
                                :class="index == activateRecommondRoute ? 'text-#437dc2' : 'text-#FFFFFF99'">
                                <SvgIcon class="w-2.1rem h-2.4rem" icon="ri:traffic-light-line" />
                                {{ item.traffic_light_count }}
                            </div>
                        </div>
                        <div class="flex  items-center justify-between"
                            :class="index == activateRecommondRoute ? 'text-#437dc2' : 'text-#FFFFFF99'">
                            <div class="text-1.8rem">{{ item.distance / 1000 }}公里</div>
                            <div class="text-1.8rem">
                                {{ item.tags.length > 0 ? item.tags[item.tags.length - 1] : '推荐' }}
                            </div>
                        </div>
                    </div>
                    <div class="w-full h-0.1rem bg-op2 " v-if="index !== recommondRoutes.length - 1"></div>
                </template>

                <div v-if="recommondRoutes.length !== 0"
                    @click="carMove(recommondRoutes[activateRecommondRoute].polyline, activateRecommondRoute, true)"
                    class="bg-#107CFB text-center text-2.2rem  w-full p-0.4rem text-white rounded-full mt-1rem mb-1.5rem cursor-pointer">
                    开始导航
                </div>
            </div>
        </div>

        <div class="w-12rem h-12rem search absolute top-5.5rem left-49.5rem z-10000 flex flex-col items-center justify-center text-#DC362E cursor-pointer"
            @click="stopNavigation('hand')" v-if="isMoving">

            <SvgIcon class="w-6rem h-6rem" icon="mdi:stop-remove-outline" />
            <span class="text-1.6rem mt-0.8rem">停止导航</span>

        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { emitter } from '@/utils/mitt';
import { dragStartFn, dragEndFn } from "@/hooks/business/drag";
import { touchEventData } from "@/hooks/business/eventListen/event";
import { eventMap, MapAction, MapWidget } from "@/hooks/business/eventListen/mapEventListen";
import { throttle } from "@/utils/common";

const ZMap = (window as any).TMap;
let oldValue = '';

let map: any = null;
let mapMarker: any = null;
var mapSearchSuggest: any = null;
var polylineLayer: any = null;

let carPosition = new ZMap.LatLng(39.980776, 116.335878)
const homePosition = new ZMap.LatLng(40.07332, 116.354512); // 家的位置
const companyPosition = new ZMap.LatLng(39.980776, 116.335878); // 公司位置

const isMoving = ref(false); // 是否正在移动
const searchKeyword = ref("");
const suggestionRoutes: any = ref([]); // 关键字搜索建议
const recommondRoutes: any = ref([]); // 推荐路径列表（选中一个进行行驶）
const activateRecommondRoute = ref(0); // 激活的推荐路径索引

// 初始化地图
function initMap() {
    map = new ZMap.Map("map", {
        center: carPosition,
        zoom: 17,
        pitch: 25,
        rotation: 0,
        viewMode: "3D",
        mapStyleId: "style1",
    });

    map.removeControl(ZMap.constants.DEFAULT_CONTROL_ID.ZOOM);
    map.removeControl(ZMap.constants.DEFAULT_CONTROL_ID.SCALE);
    map.removeControl(ZMap.constants.DEFAULT_CONTROL_ID.ROTATION);
    mapMarker = new ZMap.MultiMarker({
        map,
        styles: {
            'car-down': new ZMap.MarkerStyle({
                width: 40,
                height: 40,
                anchor: {
                    x: 20,
                    y: 20,
                },
                faceTo: 'map',
                rotate: 180,
                src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png',
            })
        },
        geometries: [
            {
                id: 'car',
                styleId: 'car-down',
                position: carPosition,
            }
        ],
    });
    // 新建一个地点搜索类
    new ZMap.service.Search({ pageSize: 3 });
    mapSearchSuggest = new ZMap.service.Suggestion({
        pageSize: 3, // 返回结果每页条目数
        region: "北京", // 限制城市范围
        regionFix: true, // 搜索无结果时是否固定在当前城市
    });
}

function dragMapStart(e: TouchEvent) {
    dragStartFn(e)
}

function dragMapEnd(e: TouchEvent) {
    dragEndFn(e, (data: touchEventData) => {
        if (data.type === 'swipe') {
            eventMap(MapAction.Swipe, MapWidget.Map, `${MapWidget.Map}_swipe`, MapWidget.Map, data);
        } else if (data.type === 'zoom') {
            eventMap(MapAction.Zoom, MapWidget.Map, `${MapWidget.Map}_zoom`, MapWidget.Map, data);
        }
    })
}



// 聚焦输入框时，清空搜索建议
function focusInput() {
    eventMap(MapAction.Click, MapWidget.SearchInput, `${MapWidget.SearchInput}_focus`, MapWidget.SearchInput);
}

// 原始 getSuggestions
function _getSuggestions() {
    recommondRoutes.value = []; // 清空路径列表
    const keyword = searchKeyword.value.trim();
    if (keyword === oldValue) {
        return;
    }
    oldValue = keyword;
    eventMap(MapAction.Input, MapWidget.SearchInput, `${MapWidget.SearchInput}_input`, MapWidget.SearchInput, keyword);
    if (keyword) {
        mapSearchSuggest
            .getSuggestions({ keyword: keyword, location: map.getCenter() })
            .then((result: any) => {
                suggestionRoutes.value = result.data;
            })
    } else {
        suggestionRoutes.value = [];
    }
}
// 包装为节流后的函数，300ms 可根据需要调整
const getSuggestions = throttle(_getSuggestions, 1000);

// 导航回家
function goHome(isHand: boolean = false) {
    if (isHand) {
        eventMap(MapAction.Click, MapWidget.SearchHistoryItem, `${MapWidget.SearchHistoryItem}0`, `${MapWidget.SearchHistoryItem}0`, "home");
    }
    var driving = new ZMap.service.Driving({
        mp: false, // 是否返回多方案
        policy: "PICKUP,NAV_POINT_FIRST", // 规划策略
    });
    driving.search({ from: carPosition, to: homePosition }).then((result) => {
        carMove(result.result.routes[0].polyline, 0, false)
    });
}
// 导航到公司
function goCompany(isHand: boolean = false) {
    if (isHand) {
        eventMap(MapAction.Click, MapWidget.SearchHistoryItem, `${MapWidget.SearchHistoryItem}1`, `${MapWidget.SearchHistoryItem}1`, "company");
    }
    var driving = new ZMap.service.Driving({
        mp: false, // 是否返回多方案
        policy: "PICKUP,NAV_POINT_FIRST", // 规划策略
    });
    driving.search({ from: carPosition, to: companyPosition }).then((result) => {
        carMove(result.result.routes[0].polyline, 0, false)
    });
}
// 搜索驾车路线
function searchDrivingRoute(endPosition: { lat: number; lng: number; height: number }, index?: number, address?: string) {
    if (address && index !== undefined) {
        eventMap(MapAction.Click, MapWidget.SearchSuggestionItem, `${MapWidget.SearchSuggestionItem}${index}`, `${MapWidget.SearchSuggestionItem}${index}`, address);
    }
    var driving = new ZMap.service.Driving({
        mp: true, // 是否返回多方案
        policy: "PICKUP,NAV_POINT_FIRST", // 规划策略
    });
    driving.search({ from: carPosition, to: endPosition }).then((result) => {
        recommondRoutes.value = result.result.routes
    });
}

function setActivateRecommondRoute(index: number) {
    activateRecommondRoute.value = index;
    eventMap(MapAction.Click, MapWidget.RecommendRouteItem, `${MapWidget.RecommendRouteItem}${index}`, `${MapWidget.RecommendRouteItem}${index}`, `选择路线${index + 1}`);
}
// 小车按照轨迹移动
function carMove(paths: { lat: number; lng: number; height: number }[], index: number, isHand: boolean = false) {
    if (isHand) {
        eventMap(MapAction.Click, MapWidget.StartNavigation, MapWidget.StartNavigation, MapWidget.StartNavigation);
    }
    recommondRoutes.value.length = 0; // 清空推荐路径
    suggestionRoutes.value.length = 0; // 清空搜索建议
    searchKeyword.value = ""; // 清空搜索关键词
    // 先删除已有 polylineLayer
    if (polylineLayer) {
        polylineLayer.setMap(null);
        polylineLayer = null;
    }
    // 创建新的折线图层
    polylineLayer = new ZMap.MultiPolyline({
        id: "polyline-layer",
        map: map,
        styles: {
            style_blue: new ZMap.PolylineStyle({
                color: "#3E98A8",  // 线填充色
                width: 4,  // 折线宽度
                borderWidth: 2, // 边线宽度
                borderColor: "rgba(255,255,255,0.5)", // 边线颜色
                lineCap: "round",
                eraseColor: 'rgba(190,188,188,0.1)',
            }),
        },
        geometries: [
            {
                id: "erasePath",
                styleId: "style_blue",
                paths: paths,
            },
        ],
    });

    // 模拟小车移动
    let lastEaseToTime = 0;
    const easeToInterval = 100; // 最小间隔1秒
    mapMarker.moveAlong(
        {
            car: {
                path: paths,
                speed: 250, // 模拟移动速度
            },
        },
        {
            autoRotation: true,
        }
    );

    mapMarker.on('moving', (e: any) => {
        isMoving.value = true;
        var passedLatLngs = e.car && e.car.passedLatLngs;
        if (passedLatLngs) {
            const roation = ZMap.geometry.computeHeading(
                e.car.passedLatLngs[e.car.passedLatLngs.length - 2],
                e.car.passedLatLngs[e.car.passedLatLngs.length - 1]
            );
            carPosition = mapMarker.getGeometryById('car').position;
            const position = ZMap.geometry.computeDestination(
                mapMarker.getGeometryById('car').position,
                roation,
                120
            );
            const now = Date.now();
            if (now - lastEaseToTime > easeToInterval) {
                map.easeTo(
                    {
                        center: position
                    },
                    {
                        duration: 1000
                    }
                );
                lastEaseToTime = now;
            }
            polylineLayer.eraseTo(
                'erasePath',
                passedLatLngs.length - 1,
                passedLatLngs[passedLatLngs.length - 1]
            );
        }
    });

    // 监听导航结束事件
    mapMarker.on('move_ended', () => {
        stopNavigation()
    });
}

function stopNavigation(type?: string) {
    if (type) {
        eventMap(MapAction.Click, MapWidget.CloseNavigation, MapWidget.CloseNavigation, MapWidget.CloseNavigation);
    }
    if (mapMarker) {
        mapMarker.stopMove();
    }
    if (polylineLayer) {
        polylineLayer.setMap(null);
        polylineLayer = null;
    }
    recommondRoutes.value.length = 0; // 清空推荐路径
    suggestionRoutes.value.length = 0; // 清空搜索建议
    searchKeyword.value = ""; // 清空搜索关键词
    isMoving.value = false;

}

emitter.on("goHome", () => {
    goHome()
})

emitter.on("goCompany", () => {
    goCompany()
})

emitter.on("closeNavigation", () => {
    stopNavigation()
})
onMounted(() => {
    initMap()
});
</script>

<style lang="scss" scoped>
.search {
    border-radius: 10px;
    background: rgba(78, 84, 141, 0.26);
    border: 1px solid undefined;
    backdrop-filter: blur(22px);
}

.bg-op2 {
    background: rgba(255, 255, 255, 0.2);
}

#map>*:last-child {
    display: none;
}
</style>
